<!-- eslint-disable @typescript-eslint/no-explicit-any -->
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  useUserCreatePostByAdminApi,
  useUserCreatePostByCommonApi,
} from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
const userStore = useUserStore()
const router = useRouter()
const text = ref('')
// 控制对话框的显示与隐藏
const dialogVisible = ref(false)
// 合并为一个对象存储数据
const articleData = ref({
  // 存储封面图片的 Base64 数据
  coverImage: '',
  // 存储文章标题
  title: '',
  // 存储发布板块分类
  category: '',
  // 存储阅读权限
  visitorDeny: false,
  // 存储评论权限
  commentDeny: false,
})
const props = defineProps<{
  articleDataProp?: {
    // 存储封面图片的 Base64 数据
    coverImage: string
    // 存储文章标题
    title: string
    // 存储发布板块分类
    category: string
    // 存储阅读权限
    visitorDeny: boolean
    // 存储评论权限
    commentDeny: boolean
  }
  textProp?: string
}>()
if (props.articleDataProp) {
  articleData.value = { ...props.articleDataProp }
  text.value = props.textProp || ''
}
// 处理图片上传
const handleFileChange = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      // 修改为对象属性赋值
      articleData.value.coverImage = e.target
        ?.result as string
    }
    reader.readAsDataURL(file)
  }
}

// 处理发布文章提交
const handlePublish = () => {
  if (
    !articleData.value.title ||
    !articleData.value.category
  ) {
    ElMessage.warning('请填写标题和选择发布板块分类')
    return
  }

  const userStore = useUserStore()
  const postData = {
    title: articleData.value.title,
    content: text.value,
    topic: articleData.value.category,
    readPermission: articleData.value.visitorDeny ? 1 : 0,
    commentPermission: articleData.value.commentDeny
      ? 1
      : 0,
    pictureBase64: articleData.value.coverImage,
  }

  const handleSuccess = () => {
    console.log('发布文章:', {
      ...articleData.value,
      content: text.value,
    })
    ElMessage.success('文章发布成功')
    dialogVisible.value = false
    router.push('/creation/manage')
  }

  const handleError = (error: any) => {
    console.error('发布文章失败:', error)
    ElMessage.error('文章发布失败，请稍后重试')
  }

  switch (userStore.user.role) {
    case 'admin':
      useUserCreatePostByAdminApi(postData)
        .then(handleSuccess)
        .catch(handleError)
      break
    case 'moderator':
      // 假设版主有专用 API，若没有可使用普通用户 API
      useUserCreatePostByCommonApi(postData)
        .then(handleSuccess)
        .catch(handleError)
      break
    default:
      useUserCreatePostByCommonApi(postData)
        .then(handleSuccess)
        .catch(handleError)
      break
  }
}
</script>

<template>
  <div class="flex create-page">
    <v-md-editor
      v-model="text"
      height="400px"
    ></v-md-editor>
    <el-button
      type="primary"
      class="publish"
      @click="dialogVisible = true"
    >
      发布文章
    </el-button>
    <el-dialog
      v-model="dialogVisible"
      title="提交文章"
      width="50%"
    >
      <!-- 修改表单绑定对象 -->
      <el-form :model="articleData" label-width="120px">
        <el-form-item label="封面图片">
          <input
            type="file"
            @change="handleFileChange"
            accept="image/*"
          />
          <img
            :src="articleData.coverImage"
            alt="封面预览"
            v-if="articleData.coverImage"
            style="max-width: 200px; margin-top: 10px"
          />
        </el-form-item>
        <el-form-item label="标题">
          <!-- 修改绑定对象属性 -->
          <el-input v-model="articleData.title" />
        </el-form-item>
        <el-form-item label="发布板块分类">
          <!-- 修改绑定对象属性 -->
          <el-select
            v-model="articleData.category"
            placeholder="请选择板块分类"
          >
            <el-option label="体育" value="体育" />
            <el-option label="生活" value="生活" />
            <el-option label="学习" value="学习" />
            <el-option
              v-if="
                userStore.user.role == 'moderator' ||
                userStore.user.role == 'admin'
              "
              label="公告"
              value="公告"
            />
            <!-- 可按需添加更多选项 -->
          </el-select>
        </el-form-item>
        <el-form-item label="阅读权限">
          <!-- 修改绑定对象属性 -->
          <el-switch
            v-model="articleData.visitorDeny"
            active-text="游客不可看"
            inactive-text="游客可看"
          />
        </el-form-item>
        <el-form-item label="评论权限">
          <!-- 修改绑定对象属性 -->
          <el-switch
            v-model="articleData.commentDeny"
            active-text="不可评论"
            inactive-text="可评论"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="handlePublish"
            >确定发布</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.create-page {
  flex-direction: column;
}
.publish {
  margin-top: 20px;
}
</style>
